﻿using System.Collections;
using UnityEngine;

public class CarWiper : MonoBehaviour
{
    public float speed;     //控制雨刮器速度
    public float radius;    //控制雨刮器半径
    public float interval;  //控制雨刮器间隔时间
    public float range;     //控制雨刮器范围内的恢复数量

    private Material mat;
    private bool isWiper;
    private bool vertical;
    private float timer;
    private float amount;
    private float angle;

    private void Awake()
    {
        mat = GetComponent<Renderer>().material;
    }

    private void Start()
    {
        StartWiper();
    }

    private void Update()
    {
        if (!isWiper)
            return;

        if (Time.time - timer < interval)
        {
            amount += Time.deltaTime * 0.1f;
            amount = Mathf.Clamp(amount, 0, range);
            mat.SetFloat("_RangeAmount", amount);
            return;
        }

        angle += Time.deltaTime * speed;
        angle = Mathf.Clamp(angle, 0, 90f);
        if (angle >= 90f)
        {
            timer = Time.time;
            angle = 0f;
            vertical = !vertical;
            mat.SetInt("_WiperAxis", vertical ? 1 : 0);
            amount = 0f;
            mat.SetFloat("_RangeAmount", amount);
        }
        mat.SetFloat("_WiperAngle", angle);
    }

    public void StartWiper()
    {
        angle = 0f;
        amount = 1f;
        isWiper = true;
        vertical = false;
        mat.SetFloat("_RangeRadius", radius);
        mat.SetFloat("_RangeAmount", amount);
        mat.SetFloat("_WiperAngle", angle);
        mat.SetInt("_WiperAxis", 0);
    }

    public void StopWiper()
    {
        isWiper = false;
        amount = 1f;
        angle = 0f;
        mat.SetFloat("_WiperAngle", angle);
        mat.SetFloat("_RangeAmount", amount);
    }
}
